import logging
from flask import render_template, session, g, abort, jsonify, request, json
from info import constants, db
from info.models import User, News, Comment, CommentLike
from info.until.common import outside
from info.until.response_code import RET
from . import news_blu


@news_blu.route('/<int:news_id>')
@outside
def detail(news_id):
    """
    显示新闻的详情页面
    :param news_id:
    :return:
    """

    # 判断用户是否登入
    use_data = g.use

    # 对点击量新闻进行排行
    new_data = []
    try:
        new_data = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        logging.error(e)

    new_data_li = []
    for new in new_data:
        new_data_li.append(new.to_basic_dict())

    # 获取详情新闻的数据
    news_detail = None
    try:
        news_detail = News.query.get(news_id)
    except Exception as e:
        logging.error(e)

    if not news_detail:
        abort(404)

    # 点击量加1，对数据库进行了修改，本来应该要commit保存，但是由于配置了SQLALCHEMY_COMMIT_ON_TEARDOWN
    # 所以在修改的时候不需要主动commit
    news_detail.clicks += 1

    # 显示评论
    new_comment_time = []
    try:
        new_comment_time = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc())
    except Exception as e:
        logging.error(e)

    # 需求显示当前新闻的当前用户点赞
    # 1.查询出当前新闻所有的评论ID
    # 2.查询出当前用户的当前新闻的点赞
    # 3.查询出需求的id
    comment_like_id= []
    if use_data:
        # 1.当前新闻所有的评论id
        new_comment_time_id= [ new_comment_times.id for new_comment_times in new_comment_time]
        # 2.当前新闻的当前用户的点赞
        new_comment_like= CommentLike.query.filter(use_data.id==CommentLike.user_id,CommentLike.comment_id.in_(new_comment_time_id)).all()
        # 3.获取点赞的评论id
        comment_like_id= [comment_ids.comment_id for comment_ids in new_comment_like]

    comments = []
    for comment in new_comment_time:
        comment_dict= comment.to_dict()
        comment_dict["is_like"]=False
        if comment.id in comment_like_id :
            comment_dict["is_like"]= True
        comments.append(comment_dict)

    is_collected = False
    # 先判断用户是否登入
    if use_data:
        # 再判断用户是否收藏过
        if news_detail in use_data.collection_news:
            is_collected = True
    # 判断用户是否关注
    is_follow= False
    if use_data and news_detail.user:
        # 判断是否关注了该作者
        if use_data in use_data.followed:
            is_follow= True


    data = {
        'use': use_data.to_dict() if use_data else None,
        'new_data_li': new_data_li,
        'news_detail': news_detail.to_dict(),
        'is_collected': is_collected,
        'comments': comments,
        'is_follow':is_follow
    }

    return render_template('detail.html', data=data)


@news_blu.route('/news_collect', methods=["post"])
@outside
def news_collect():
    """
    1.获取参数
    2.判断参数
    3.查询数据库
    4.收藏或者取消收藏
    5.返回数据
    :return:
    """

    use = g.use
    if not use:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登入")

    params = json.loads(request.data)
    news_id = params.get("news_id")
    action = params.get("action")

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 查询数据库,判断新闻是否在数据库中
    try:
        result = News.query.filter(News.id == news_id).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库查询错误")
    if not result:
        return jsonify(errno=RET.DATAERR, errmsg="数据不存在")

    if action == "collect":
        # 收藏,判断是否收藏
        if result not in use.collection_news:
            use.collection_news.append(result)
    else:
        if result in use.collection_news:
            use.collection_news.remove(result)

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route('/news_comment', methods=["post"])
@outside
def news_comment():
    """
    评论新闻
    :return:
    """
    use = g.use
    if not use:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登入")

    # 取参
    params = request.json
    news_id = params.get("news_id")
    use_comment = params.get("comment")
    parent_id = params.get("parent_id")

    if not all([news_id, use_comment]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if parent_id:
        try:
            parent_id = int(parent_id)
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        result = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not result:
        return jsonify(errno=RET.NODATA, errmsg="无此新闻")

    # 添加数据在评论表中
    comment = Comment()
    comment.user_id = use.id
    comment.news_id = news_id
    comment.content = use_comment
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        logging.error(e)
        return jsonify(errno=RET.IOERR, errmsg="添加数据库失败")
    return jsonify(errno=RET.OK, errmsg="OK", data=comment.to_dict())


@news_blu.route('/comment_like', methods=["post"])
@outside
def comment_like():
    """
    点赞
    :return:
    """
    use = g.use
    if not use:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登入")
    data_json = request.json
    comment_id = data_json.get("comment_id")

    action = data_json.get("action")

    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        comment_id = int(comment_id)

    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    results = None
    try:
        results = Comment.query.get(comment_id)
    except Exception as e:
        logging.error(e)

    if not results:
        return jsonify(errno=RET.NODATA, errmsg="评论不存在")

    # 点赞或者取消点赞
    try:
        result = CommentLike.query.filter(CommentLike.comment_id == comment_id, CommentLike.user_id == use.id).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if action == "add":
        if not result:
            comment_model_like = CommentLike()
            comment_model_like.user_id = use.id
            comment_model_like.comment_id = comment_id
            db.session.add(comment_model_like)
            results.like_count += 1
    else:
        if result:
            db.session.delete(result)
            results.like_count -= 1
    try:

        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg="数据操作失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@news_blu.route('/news_follow',methods=["post"])
@outside
def news_follow():
    """
    关注和取消关注
    :return:
    """
    use= g.use
    if not use:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登入")
    user_id= request.json.get("user_id")
    action= request.json.get("action")

    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    try:
        user_id= int(user_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    if action not in ["follow","unfollow"]:
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        other= User.query.get(user_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="数据库查询错误")
    if not other:
        return jsonify(errno=RET.NODATA,errmsg="未查询到该作者")
    # 关注和取消关注
    if action=="follow":
        if other not in use.followed:
            other.followers.append(use)
    else:
        if other in use.followed:
            other.followers.remove(use)

    return jsonify(errno=RET.OK,errmsg="ok")




